<script lang="ts" setup>
import { ref, watch, onMounted, nextTick, computed } from 'vue';
import MEcharts from '/@/components/MEcharts/MEcharts.vue';
const props = defineProps({
  data: { type: [Object, Array], required: true },
});

const chartRef = ref();
const myChart = ref<InstanceType<typeof MEcharts>>();

// 兼容数组和对象格式，优先取数组
const pieData = computed(() => {
  if (Array.isArray(props.data)) return props.data;
  if (props.data && typeof props.data === 'object') {
    // 取第一个key对应的数组
    const arr = Object.values(props.data).find(v => Array.isArray(v));
    return arr || [];
  }
  return [];
});

const validPieData = computed(() => pieData.value.filter((i: any) => i.value > 0));
const noData = computed(() => !validPieData.value.length);

const option = ref<any>({
  series: [
    {
      animationDelay() {
        return Math.random() * 400;
      },
      animationEasing: 'exponentialInOut',
      animationType: 'scale',
      center: ['50%', '40%'], // 将饼图向上移动，为下方标签留出空间
      color: ['#5ab1ef', '#8e7cc3', '#b6a2de', '#67e0e3', '#2ec7c9'],
      data: [],
      name: '占比',
      radius: '60%', // 减小饼图半径，为标签留出更多空间
      roseType: 'radius',
      type: 'pie',
      label: { 
        show: true, 
        color: '#fff', 
        formatter: function(params: any) {
          // 显示原始值而不是ECharts计算的百分比
          return `${params.name}: ${params.value}%`;
        },
        position: 'outside',
        alignTo: 'none', // 不使用边缘对齐
        distanceToLabelLine: 10,
        fontSize: 11,
        lineHeight: 14
      },
      labelLine: {
        show: true,
        length: 20,
        length2: 15,
        smooth: false,
        lineStyle: {
          color: '#fff',
          width: 1
        }
      },
      itemStyle: { borderRadius: 8, borderColor: '#222', borderWidth: 2 },
    },
  ],
  tooltip: { 
    trigger: 'item',
    formatter: function(params: any) {
      // 提示框也显示原始值
      return `${params.name}: ${params.value}%`;
    }
  },
 
});

const updateChart = () => {
  option.value.series[0].data = validPieData.value;
  myChart.value?.resizeHandler && myChart.value.resizeHandler();
};

watch(pieData, () => nextTick(updateChart), { deep: true, immediate: true });
onMounted(() => nextTick(updateChart));

defineExpose({
  updateChart,
  chartRef,
});
</script>
<template>
  <div ref="chartRef" class="chart-container" style="position:relative;">
    <m-echarts :option="option"></m-echarts>
    <div v-if="noData" class="no-data">暂无数据</div>
  </div>
</template>
<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
.no-data {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #aaa;
  font-size: 18px;
  z-index: 2;
}
</style>
